import os
import sys
import re
from typing import Dict, Any

from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from config import REVIEWER_PROMPT
from agents.base_agent import BaseAgent

class ReviewerAgent(BaseAgent):
    def __init__(self, vector_store=None,file_path=None):
        super().__init__("评审员")
        self.vector_store = vector_store
        self.file_path = file_path
        self.retriever = vector_store.as_retriever(search_kwargs={"k": 5}
        )
        # 加载提示词
        with open(REVIEWER_PROMPT, 'r', encoding='utf-8') as f:
            reviewer_template = f.read()
        
        # 创建提示模板
        self.prompt = PromptTemplate(
            template=reviewer_template,
            input_variables=["programmer_details", "relevant_context"]
        )
    
    def _get_relevant_context(self, file_path, function_name):
        """获取与指定文件相关的上下文"""
        query = f"文件 {file_path} 中 {function_name}的代码精准内容和作用，以及该文件的主要作用"
        
        # 获取相关文档
        docs = self.retriever.invoke(query)
        
        # 返回相关文档的内容
        return "\n".join([doc.page_content for doc in docs])
    
    def review_documentation(self, programmer_output,function_name):
        """评审文档并提供反馈"""
        programmer_details = programmer_output if isinstance(programmer_output, str) else "\n".join([p for p in programmer_output if p])
        
        # 获取相关上下文
        relevant_context = self._get_relevant_context(programmer_details,function_name)
        
        # 准备输入
        inputs = {
            'programmer_details': programmer_details,
            'relevant_context': relevant_context
        }
        
        # 使用流式输出运行
        review_result = self.run_with_streaming(
            self.prompt,
            inputs,
            step="评审文档"
        )
        
        score_match = re.search(r'(?:分数[评估]*[:：]\s*)?([\d.]+)[\/\s]*10', review_result)
        score = float(score_match.group(1)) if score_match else 0

        
        return {
            'score': score,
            'review': review_result,
            'inputs': {
                'programmer_details_length': len(programmer_details)
            }
        }
